package cn.scy.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.Security;

/**
 * SM4 加解密工具类
 *
 * @author scy
 */
public final class Sm4Util {

    private static final String ENCODING = StandardCharsets.UTF_8.name();
    private static final String ALGORITHM_NAME = "SM4";
    private static final String PADDING = "SM4/ECB/PKCS5Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private Sm4Util() {
    }

    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    public static String encryptEcb(String key, String plainText) throws Exception {
        byte[] keyData = key.getBytes(ENCODING);
        byte[] strData = plainText.getBytes(ENCODING);
        byte[] array = encryptEcbPadding(keyData, strData);
        return ByteUtils.toHexString(array);
    }

    public static String decryptEcb(String key, String encryptText) throws Exception {
        byte[] keyData = key.getBytes(ENCODING);
        byte[] srcData = ByteUtils.fromHexString(encryptText);
        byte[] array = decryptEcbPadding(keyData, srcData);
        return new String(array, ENCODING);
    }

    private static byte[] encryptEcbPadding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    private static byte[] decryptEcbPadding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    }

}
